package com.jp.study.Interceptor;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.jp.study.annotation.LoggerAnnotation;  
  
/**
 * 
* @author dinghao
* @ClassName: LoggerInterceptor 
* @Description: 记录Controller层的进入和离开的时间,并计算其过程的时间
* @date 2018年3月21日 上午9:58:24 
*
 */
public class LoggerInterceptor extends HandlerInterceptorAdapter{  
  
    private Logger logger = LoggerFactory.getLogger(LoggerInterceptor.class); 
    
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSXXX");
  
    @Override  
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {  
        HandlerMethod handlerMethod = (HandlerMethod)handler;  
        Method method = handlerMethod.getMethod();  
        //获取当前方法上的指定注解  
        LoggerAnnotation loggerAnnotation = method.getAnnotation(LoggerAnnotation.class);  
        //判断当前注解是否存在  
        if(loggerAnnotation != null){  
            long startTime = System.currentTimeMillis();  
            request.setAttribute("startTime",startTime);  
            String startTimeFormat = sdf.format(new Date(startTime));
            logger.info("进入" + method.getName() + "方法的时间是：" + startTimeFormat);  
        }  
        return true;  
    }  
  
    @Override  
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {  
        HandlerMethod handlerMethod = (HandlerMethod)handler;  
        Method method = handlerMethod.getMethod();  
        //获取当前方法上的指定注解  
        LoggerAnnotation loggerAnnotation = method.getAnnotation(LoggerAnnotation.class);  
        //判断当前注解是否存在  
        if(loggerAnnotation != null){  
            long endTime = System.currentTimeMillis();  
            long startTime = (Long) request.getAttribute("startTime");  
            long periodTime = endTime - startTime; 
            String startTimeFormat = sdf.format(new Date(endTime));
            logger.info("离开" + method.getName() + "方法的时间是：" + startTimeFormat);  
            logger.info("在" + method.getName() + "方法的时长是：" + periodTime + "ms");  
        }  
    }  
}  
